/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.netbuilder.services.equipment;

import com.google.code.netbuilder.dal.entities.EquipmentTemplate;
import com.google.code.netbuilder.dal.providers.IEquipmentTemplateProvider;
import com.google.code.netbuilder.logging.NetBuilderLogger;
import com.google.code.netbuilder.logging.NetBuilderLoggerFactory;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 *
 * @author VIME0812
 */
@ManagedBean
@RequestScoped
public class EquipmentTemplateService {

    private static final NetBuilderLogger LOGGER = NetBuilderLoggerFactory.getNetBuilderLogger(EquipmentTemplateService.class);
    private PreparedEquipment pe;
    @EJB
    private IEquipmentTemplateProvider etp;

    private List<String> types;
    /**
     * Creates a new instance of EquipmentTemplateService
     */
    public EquipmentTemplateService() {
        types = new ArrayList<String>();
        types.add("Optical");
        types.add("Copper");
    }

    public PreparedEquipment getPe() {
        return pe;
    }

    public void setPe(PreparedEquipment pe) {
        this.pe = pe;
    }

    public String saveEquipmentTemplate() throws JAXBException {
        LOGGER.entry();
        LOGGER.debug("temp = {}", pe);
        List<EquipmentTemplate> eqipmentTemplate = etp.findAll();
        for(EquipmentTemplate et: eqipmentTemplate){
			if (et.getName().equals(pe.getPrototypeName()))
                return LOGGER.exit("Equipment template didn't create. "
                        + "Cause: template with this name already exists");
		}
        JAXBContext jaxbContext = JAXBContext.newInstance(PreparedEquipment.class);
        Marshaller m = jaxbContext.createMarshaller();
        Writer w = new StringWriter();
        m.marshal(pe, w);
        EquipmentTemplate et = new EquipmentTemplate();
        et.setName(pe.getPrototypeName());
        et.setXml(w.toString());
        etp.save(et);
        init();
        return LOGGER.exit("/eqtemplate/Create");
    }

    @PostConstruct
    public void init() {
        pe = new PreparedEquipment();
    }

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }    
}